package jp.oesf.malfoy.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jp.oesf.malfoy.dao.RssEntity;
import jp.oesf.malfoy.model.RssBean;
import jp.oesf.malfoy.model.RssRirekiBean;
import jp.oesf.malfoy.rss.IRssService;
import jp.oesf.malfoy.rss.RssConst;
import jp.oesf.malfoy.rss.RssReceiver;
import jp.oesf.malfoy.rss.RssService;
import jp.oesf.malfoy.xml.RowModel;
import jp.oesf.malfoy.xml.XmlParser;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainUi extends ListActivity {

	private final String TAG = "MainUi";

	RssEntity rssEntity = new RssEntity(this);

	String rssDetail = null;
	// String[] rssDetails =null;

	List<String> rssTag = new ArrayList<String>();
	String rssDatail;
	String[] rssDatails = null;

	ArrayAdapter<String> adapter = null;

	IntentFilter intentFilter;
	RssReceiver receiver;

	private IRssService service;
	private ServiceConnection connection = new ServiceConnection() {

		public void onServiceDisconnected(ComponentName name) {
			service = null;
		}

		public void onServiceConnected(ComponentName name, IBinder ibinder) {
			service = IRssService.Stub.asInterface(ibinder);
		}
	};

	private Object list;

	private Object xmlParser;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		receiver = new RssReceiver();
		intentFilter = new IntentFilter();
		intentFilter.addAction(RssConst.RSS_MSG_ACTION);
		registerReceiver(receiver, intentFilter);

		// サービスを開始する
		Intent intent = new Intent(this, RssService.class);
		intent.putExtra(RssConst.RSS_SERVICE_TAG, RssConst.RSS_URL);
		startService(intent);

		// サービスに接続する
		bindService(intent, connection, BIND_AUTO_CREATE);

		adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);

		Spinner spinner = (Spinner) findViewById(R.id.spinner);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			public void onNothingSelected(AdapterView<?> parent) {

			}

			public void onItemSelected(AdapterView<?> parent,
					android.view.View view, int position, long id) {

				String RssResult = null;

				RssRirekiBean testBean2 = new RssRirekiBean();
				List<RssBean> rssBeans2 = new ArrayList<RssBean>();
				List<RssRirekiBean> listRssRirekiBean2 = new ArrayList<RssRirekiBean>();

				if (rssEntity.selectAllRssData(
						(String) parent.getSelectedItem(), rssBeans2) == -1) {
					alert("Error", "履歴を取得できませんでした", true);
				}

				for (RssBean rssBean : rssBeans2) {
					rssTag.add(rssBean.getTitle());
//					rssDetail=rssDetail+"aaa"+rssBean.getId()+"\n"+rssBean.getTitle()+"\n"+rssBean.getRireki_key()+"\n"+rssBean.getLink()+"\n"+rssBean.getDescription()+"\n"+rssBean.getPubDate()+"\n"+rssBean.getCategory();
				}

				
				
				ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(
						MainUi.this, R.layout.list_row, rssTag);

				setListAdapter(adapter2);
			}
		});
	}

	public void onClickEndButton(View view) {
		// サービスの接続を解除する
		unbindService(connection);

		// サービスを終了する
		stopService(new Intent(this, RssService.class));
		Toast.makeText(this, "終了しました", Toast.LENGTH_LONG).show();
		// finish();
	}

	public void onClickConfigButton(View view) {
		Intent intent = new Intent(this, ConfigUi.class);
		startActivity(intent);
		Toast.makeText(this, "設定画面", Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onListItemClick(ListView listView, View view, int position,
			long id) {
		super.onListItemClick(listView, view, position, id);
		Intent intent = new Intent(this, DetailUi.class);

		TextView textView = (TextView) findViewById(R.id.title_text);
		
			RssBean rssBean=new RssBean();
			int pk=70+position;
			String fk="1";
			
			long res=rssEntity.selectRssData(pk,"1",rssBean);
		if (res == -1) {
			alert("Error", "詳細を取得できませんでした", true);
		}
		
		rssDetail="Id:"+rssBean.getId()+"\nTitle:"+rssBean.getTitle()+"\nRireki_key:"+rssBean.getRireki_key()+"\nLink:"+rssBean.getLink()+"\nDescription:"+rssBean.getDescription()+"\nPubDate:"+rssBean.getPubDate()+"\nCategory:"+rssBean.getCategory();
//		alert("Error", rssDetail, true);
		
		
		intent.putExtra("rssTag", rssDetail);
//		intent.putExtra("rssTag", textView.getText());


		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// String xml = null;
		String xml1 = "gettingRSS";
		XmlParser xmlParser;
		xmlParser = XmlParser.getInstance();
		String xml;
		try {
			// XMLを取得する
			xml = service.getXml();
			// XMLを解析する
			list = xmlParser.parseSax(this, xml);
		} catch (Exception e) {
			e.printStackTrace();
			xml = "error";
		}
		TextView text = (TextView) findViewById(R.id.textRss);
		 text.setText(xml1);
//		text.setText("");
		 
		 
		 

		RssRirekiBean testBean = new RssRirekiBean();

		List<RssBean> rssBeans = new ArrayList<RssBean>();
		List<RssRirekiBean> listRssRirekiBean = new ArrayList<RssRirekiBean>();
		if (text.getText().toString().isEmpty()
				|| text.getText().toString() == null
				|| text.getText().toString().equals("")) {

			long resultXml = rssEntity.selectAllRssData(xml, rssBeans);

			 if (resultXml == -1) {
//			if (false) {

				alert("Error", "URLを取得できませんでした", true);
				adapter.add("URLを取得できませんでした");

				/*
				 * Log.v(TAG, "sendBroadcast()"); Intent intent = new Intent();
				 * intent.putExtra(RssConst.RSS_RECEIVER_TAG, "URLを取得できませんでした");
				 * intent.setAction(RssConst.RSS_MSG_ACTION);
				 * sendBroadcast(intent);
				 */

			} else {
				// alert("Error", "DBからURLを取得できました", true);
				// DBからデータを取得
				rssEntity.selectAllRirekiData(listRssRirekiBean);
				for (RssRirekiBean rssRirekiBean : listRssRirekiBean) {
					adapter.add(rssRirekiBean.getUrl());
				}
			}
		} else {
			adapter.add(RssConst.RSS_URL);

/*			// てすとでーた
			for (int i = 0; i < 10; i++) {
				RssBean rssBean = new RssBean();
				rssBean.setTitle("Titleあ" + i);
				rssBean.setLink("Linkい" + i);
				rssBean.setDescription("descriptionう" + i);
				rssBean.setPubDate("pubDateえ" + i);
				rssBean.setCategory("categoryお" + i);
				rssBeans.add(rssBean);
			}
			// てすとでーた終了
*/
			testBean.setListRssData(rssBeans);
			testBean.setUrl(RssConst.RSS_URL);
			rssEntity.setData(testBean);

		}
		return true;
	}

	public void alert(String title, String message, boolean positive) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setMessage(message);
		if (positive) {
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {

						}
					});
		}
		builder.show();
	}
}
